<template>
	<view>
		<view class="map">
			<!-- 站点接送 -->
			<view v-if="goPickType == 1 || backPickType == 1" class="map-wrap">
				<map id="map" style="width: 100%; height: 100vh;" :latitude="latitude" :longitude="longitude" :markers="covers"
				 :polyline="polyline" :include-points="covers" @markertap="handleChooseBusStation">
				</map>
			</view>
			<!-- 区域接送 -->
			<!-- #ifdef MP-WEIXIN -->
			<view v-if="goPickType == 2 || backPickType == 2" class="map-wrap">
				<map id="map" style="width: 100%; height: 100vh;" :latitude="latitude" :longitude="longitude" :markers="covers"
				 :polyline="polyline" :polygons="polygons" :include-points="covers" @tap="handleTapMap">
				</map>
			</view>
			<!-- #endif -->
			<view class="level_align tp-ptb0lr30">
				<view class="tp-mr20 tp-h64 tp-bgf tp-br40 center_combo tp-ptb0lr20 tp-wsn" @click="pageJumps('/pagesSecond/make/selectCity?type=go')">
					<uni-icons class="tp-mr10" type="location-filled" size="14" color="#999"></uni-icons>
					{{city}}
				</view>
				<view class="controls-title flex-1">
					<view class="input">
						<input type="text" v-model="searchText" placeholder="输入地址名称" @input="handleSearchAddress(searchText)" />
					</view>
				</view>
			</view>

			<view class="list">
				<view class="item" v-for="(item, index) in searchAddressList" :key="index" @click="handleChooseAddress(item)">
					<view class="tit">{{item.title}}</view>
					<view class="address">{{item.address}}</view>
				</view>
			</view>

			<view class="choosed_address-wrap">
				<view class="choosed_address">
					<text class="tip">{{txt}}：</text>
					{{(curChoosedAddress && curChoosedAddress.title) || (curChoosedAddress && curChoosedAddress.address) || '定位中...'}}
				</view>
				<view class="btn" @click="handleConfirmChooseAddress">确定</view>
			</view>

		</view>
		<!-- 定位权限提示框 S -->
		 <uni-popup type="center" ref="locationHint" :maskClick="false">
			<view class="hint-wrap tp-br20 tp-bgf ">
				<view class="tp-tc tp-lh98 tp-fc333 tp-fz30 tp-fw600">
					提示
				</view>
				<view class="hint-content center_combo">
					<view class="flex flex_column tp-fc333 tp-fz24 tp-lh44">
						请打开小程序的定位权限
					</view>
				</view>
				<view class="level_align flex_around tp-ptb0lr50 tp-mt20">
					<view @click="openSetting" class="tp-bc  tp-fcF tp-h64 tp-lh64 tp-w520 tp-tc tp-fz30 tp-br8">
						去设置
					</view>
				</view>
			</view>
		</uni-popup> 
		<!-- 定位权限提示框 E -->
	</view>
</template>

<script>
	import {
		BD09ToGCJ02
	} from '../utils/gcoord.js'
	var QQMapWX = require('@/utils/qqmap-wx-jssdk/qqmap-wx-jssdk.min.js');
	var qqmapsdk;
	import $DB from '@/utils/debounce.js'
	export default {
		data() {
			return {
				travelsStatus: '', // to出发地选择 | form目的地选择
				city: '', // 城市
				title: 'map',
				latitude: 39.90960,
				longitude: 116.39722,
				searchText: '',
				searchAddressList: [],
				curChoosedAddress: {},
				covers: [], // 地图上的标记点
				polyline: [], // 地图上的标记点连线
				busInfo: {},
				polygons: [], // 区域的数组
				stationType: 0, //  1.固定点 2.区域点 3.不接送

				goPickType: null, // 	出发站接送类型 1.固定点 2.范围点 3.不接送
				backPickType: null, // 终点站接送类型 1.固定点 2.范围点 3.不接送
				
				txt: '当前位置', // 当前位置  还是 选择位置
				nowAddLat: [], // 当前位置的坐标信息
			}
		},
		onLoad(opt) {
			this.$store.commit('delChoosedMakeCity')
			this.city = this.$store.getters.getChangeNowCity
			this.initMap();
			this.goPickType = opt && opt.goPickType
			this.backPickType = opt && opt.backPickType

			this.travelsStatus = opt && opt.travelsStatus
			this.busInfo = opt && opt.busInfo && JSON.parse(opt.busInfo)
		},
		onShow() {
			if(this.$store.getters.getChoosedMakeCity.goCity){
				this.city = this.$store.getters.getChoosedMakeCity.goCity
			}
			this.getCoversAndDrawLine() // 获取站点或者区域数据
		},
		methods: {
			// 切换城市
			changeCity(){
				
			},
			// 获取站点或者区域数据
			getCoversAndDrawLine() { // 获取地图上的标记点
				let type = this.travelsStatus == 'to' ? 0 : 1
				let {
					schedulingId,
					lineId
				} = this.busInfo
				// 大巴接送 pickUpServer , 返回的msg表明了返回的类型   1.固定点 2.区域点 3.不接送
				this.$http.get(this.$api.getPickuperStationList + '?clientType=miniapp&schedulingId=' + schedulingId + '&lineId=' +
					lineId + '&type=' +
					type).then(res => {
					if (res.code === 200) {
						this.stationType = res.data.goPickType || res.data.backPickType
						this.getLocation();

						if (this.goPickType == 1 || this.backPickType == 1) { // 固定点
							if (this.goPickType) { // 出发站
								res.data.goPoint.map(item => {
									let result = BD09ToGCJ02({
										latitude: item.lat - 0,
										longitude: item.lng - 0
									})
									item.lat = item.latitude = result[1] + ''
									item.lng = item.longitude = result[0] + ''
									item.iconPath = '/static/imgs/icons/bus1-icon.png'
									item.callout = {
										content: item.stationName,
										display: 'ALWAYS'
									}
								})
								this.covers = res.data.goPoint

							} else { // 终点站
								res.data.backPoint.map(item => {
									let result = BD09ToGCJ02({
										latitude: item.lat - 0,
										longitude: item.lng - 0
									})
									item.lat = item.latitude = result[1] + ''
									item.lng = item.longitude = result[0] + ''
									item.iconPath = '/static/imgs/icons/bus1-icon.png'
									item.callout = {
										content: item.stationName,
										display: 'ALWAYS'
									}
								})
								this.covers = res.data.backPoint
							}
							this.getBusStation()

						} else if (this.goPickType == 2 || this.backPickType == 2) { // 范围点
							if (this.goPickType) { // 出发站
								this.polygons = res.data.goPoint
							} else { // 终点站
								this.polygons = res.data.backPoint
							}
						}
					}
				})
			},
			// 判断是否在区域内
			windingNumber(p, poly) {
				var px = p.longitude, // 经度
					py = p.latitude, // 纬度
					sum = 0

				for (var i = 0, l = poly.length, j = l - 1; i < l; j = i, i++) {
					var sx = poly[i].longitude,
						sy = poly[i].latitude,
						tx = poly[j].longitude,
						ty = poly[j].latitude

					// 点与多边形顶点重合或在多边形的边上
					if ((sx - px) * (px - tx) >= 0 && (sy - py) * (py - ty) >= 0 && (px - sx) * (ty - sy) === (py - sy) * (tx - sx)) {
						return 'on'
					}

					// 点与相邻顶点连线的夹角
					var angle = Math.atan2(sy - py, sx - px) - Math.atan2(ty - py, tx - px)

					// 确保夹角不超出取值范围（-π 到 π）
					if (angle >= Math.PI) {
						angle = angle - Math.PI * 2
					} else if (angle <= -Math.PI) {
						angle = angle + Math.PI * 2
					}

					sum += angle
				}

				// 计算回转数并判断点和多边形的几何关系
				return Math.round(sum / Math.PI) === 0 ? false : true
			},



			// 初始化地图
			initMap() {
				qqmapsdk = new QQMapWX({
					key: 'C7JBZ-VQD6D-BVZ4C-PHTJO-HNPSF-ORFT5'
				});
			},
			// 当前的经纬度当前的位置
			getLocation() {
				let _this = this
				uni.getLocation({
					type: 'gcj02',
					success: async function(res) {
						let {
							latitude,
							longitude
						} = res
						// latitude = 34.767850499999994
						// longitude = 113.63227850000001

						_this.latitude =  parseFloat((latitude).toFixed(5)) // 当前位置的纬度
						_this.longitude =  parseFloat((longitude).toFixed(5)) // 当前位置的经度
						// #ifdef MP-WEIXIN
						_this.txt = '当前位置'
						_this.reverseGeocoder(_this.latitude, _this.longitude)
						if (_this.goPickType == 2 || _this.backPickType == 2) { // 在区域内使用当前位置，不在区域内 使用区域中心点
							if (_this.windingNumber({
									latitude,
									longitude
								}, _this.polygons[0].points)) {
								_this.latitude =  parseFloat((latitude).toFixed(5)) // 当前位置的纬度
								_this.longitude =  parseFloat((longitude).toFixed(5)) // 当前位置的经度
								console.log('在区域内');
							} else {
								_this.initDistrictDot(_this.polygons[0].points)
							}
						} else { // 站点接送
							_this.latitude =  parseFloat((latitude).toFixed(5)) // 当前位置的纬度
							_this.longitude =  parseFloat((longitude).toFixed(5)) // 当前位置的经度
						}
						// #endif

					


						if (_this.goPickType == 2 || _this.backPickType == 2) {
							_this.initDistrictDot(_this.polygons[0].points)
						}


						
						if (_this.travelsStatus === 'to') { // 将当前定位
							_this.nowAddLat = [{
								id: 0,
								latitude,
								longitude,
								iconPath: '/static/imgs/icons/now.png',
								width: 34,
								height: 34,
							}]
						} else if (_this.travelsStatus === 'from') {
							_this.nowAddLat = [{
								id: 0,
								latitude,
								longitude,
								iconPath: '/static/imgs/icons/now.png',
								width: 34,
								height: 34,
							}]
						}
						let obj = [{
								id: 1,
								latitude:  parseFloat((_this.latitude).toFixed(5)),
								longitude:  parseFloat((_this.longitude).toFixed(5)),
								iconPath: '/static/imgs/icons/xuan.png',
								width: 18,
								height: 34,
							}]
						if (_this.goPickType == 2 || _this.backPickType == 2) {  // 区域
							_this.covers = [...obj, ..._this.nowAddLat]
						}else {
							_this.covers = [..._this.covers, ..._this.nowAddLat]
						}
					},
					fail() {
						_this.$refs.locationHint.open()
						// uni.showToast({
						// 	title: '定位失败',
						// 	icon: 'none'
						// })
					}
				});
			},
			//  打开设置
			openSetting(){
				let _this = this
				this.$refs.locationHint.close()
				uni.openSetting({
				  success(res) {
					if(res.authSetting['scope.userLocation']){
						uni.showToast({
							title: '打开成功',
							icon: 'success'
						})
					} else {
						_this.$refs.locationHint.open()
						uni.showToast({
							title: '小程序定位权限打开失败',
							icon: 'none'
						})
					}
				  },
				  fail(e) {
				  	console.log(e);
				  }
				});
			},
			// 地址逆解析
			reverseGeocoder(latitude, longitude) {
				let _this = this
				qqmapsdk.reverseGeocoder({
					location: {
						latitude,
						longitude
					},
					success: function(res) {
						console.log('地址逆解析',res.result);
						_this.curChoosedAddress = res.result
						_this.curChoosedAddress.address = _this.curChoosedAddress.formatted_addresses.recommend
					},
				});
			},
			// 搜索地址
			handleSearchAddress: $DB(function(text) {
				let _this = this
				qqmapsdk.search({
					keyword: text,
					region: _this.city,
					success: function(res) {
						_this.searchAddressList = res.data
					},
					fail: function(res) {
						// uni.showToast({
						// 	title: '地址搜索失败',
						// 	icon: 'none'
						// })
						_this.searchAddressList = []
					}
				})
			}, 250),
			// 点击搜索出来的地址列表
			handleChooseAddress(item) {
				this.curChoosedAddress = item

				let {
					lat,
					lng
				} = item.location
				this.latitude =  parseFloat((lat).toFixed(5))
				this.longitude =  parseFloat((lng).toFixed(5))

				this.searchText = ''
				this.searchAddressList = []
			},
			// 点击地图时触发
			async handleTapMap(e) {
				// #ifdef MP-WEIXIN
				
				let {
					latitude,
					longitude
				} = e.detail
				if (this.windingNumber({
						latitude,
						longitude
					}, this.polygons[0].points)) {
					// console.log('在区域内');
					// #ifdef MP-WEIXIN
					this.covers = []
					let obj = [{
						id: 1,
						latitude:  parseFloat((latitude).toFixed(5)),
						longitude: parseFloat((longitude).toFixed(5)),
						iconPath: '/static/imgs/icons/xuan.png',
						width: 18,
						height: 34,
					}]
					// this.covers.push(obj)
					this.covers = [...obj, ...this.nowAddLat]
					this.latitude =  parseFloat((latitude).toFixed(5))
					this.longitude =  parseFloat((longitude).toFixed(5))
					this.txt = '选择位置'
					this.reverseGeocoder(latitude, longitude)
					// #endif

				} else {
					// console.log('不在区域内');
					uni.showToast({
						title: '当前位置无法提供上门接送',
						icon: 'none'
					})
				}
				// #endif

			},
			// 点击标记点时触发，e.detail = {markerId}
			handleChooseBusStation(e) {
				// console.log('点标记站点');
				let {
					markerId
				} = e.detail
				// console.log(e.detail);
				this.covers.forEach(item => {
					if (item.id == markerId) {
						// let {latitude, longitude} = item
						// this.reverseGeocoder(latitude, longitude)
						this.curChoosedAddress = item
						this.curChoosedAddress.title = item.stationName
						this.curChoosedAddress.address = item.stationName
						this.curChoosedAddress.addressName = item.address
					}
				})
			},
			// 点击确定
			handleConfirmChooseAddress() {

				if (this.goPickType == 1 || this.backPickType == 1) {
					// if ((this.goPickType == 1 || this.backPickType == 1) && this.latitude == (this.curChoosedAddress.location && this.curChoosedAddress.location.lat) || this.latitude == this.curChoosedAddress.lat) {
					let add = this.curChoosedAddress.title || this.curChoosedAddress.address
					let noTrue = true
					this.covers.forEach(item => {
						if (item.stationName && item.stationName == add) {
							noTrue = false
						}
					})
					if (noTrue) {
						return uni.showToast({
							title: '请选择接送站点',
							icon: 'none'
						})
					}
				} else if (this.goPickType == 2 || this.backPickType == 2) { // 范围点
					let latitude = this.curChoosedAddress.location.lat,
						longitude = this.curChoosedAddress.location.lng;
					if (this.windingNumber({
							latitude,
							longitude
						}, this.polygons[0].points)) {
						console.log('在区域内');
					} else {
						// console.log('不在区域内');
						return uni.showToast({
							title: '当前位置无法提供上门接送',
							icon: 'none'
						})
					}
				}
				this.$store.commit('upPickuperChoosedAddressObj', {
					[this.travelsStatus]: this.curChoosedAddress
				})
				uni.navigateBack({
					delta: 1
				})
			},
			// 初始化区域中心点
			async initDistrictDot(arr) {
				// #ifdef MP-WEIXIN
				var MaxX = 0,
					MinX = 0,
					MaxY = 0,
					MinY = 0,
					xArr = [],
					yArr = [];
				arr.forEach(item => {
					xArr.push(item.longitude)
					yArr.push(item.latitude)
				})
				MaxX = Math.max(...xArr)
				MinX = Math.min(...xArr)
				MaxY = Math.max(...yArr)
				MinY = Math.min(...yArr)
				this.longitude =  parseFloat((MinX + (MaxX - MinX) / 2).toFixed(5))
				this.latitude =  parseFloat((MinY + (MaxY - MinY) / 2).toFixed(5))
				let obj = [{
					id: 1,
					latitude:   parseFloat((this.latitude).toFixed(5)),
					longitude:  parseFloat((this.longitude).toFixed(5)),
					iconPath: '/static/imgs/icons/xuan.png',
					width: 18,
					height: 34,
				}]
				// this.covers.push(obj)
				this.covers = [...obj, ...this.nowAddLat]
				// #endif


		


				setTimeout(() => {
					// #ifdef MP-WEIXIN
					this.reverseGeocoder(this.latitude, this.longitude)
					// #endif

				}, 200)
				
			},
			getBusStation() {
				let mapCtx = uni.createMapContext("map", this)
				let padding = [100, 0, 100, 0]
				let points = this.covers
				mapCtx.includePoints({
					points,
					padding
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.map-wrap {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		/* #ifdef MP-WEIXIN */
		z-index: -1;
		/* #endif */
	}

	.controls-title {
		// width: 600rpx;
		height: 64rpx;
		margin: 18rpx auto;
		border-radius: 32rpx;
		background-color: #fff;
		display: flex;
		align-items: center;

		.address-wrap {
			font-size: 26rpx;
			display: flex;
			width: 152rpx;
			justify-content: space-evenly;
			color: $blue;
			border-right: 1px solid #ccc;

			.location-icon {
				width: 22rpx;
				height: 28rpx;
			}
		}

		.input {
			flex: 1;
			background: url(@/static/imgs/icons/search-icon.png) no-repeat left 120rpx center;
			background-size: 26rpx 26rpx;
			padding: 0 40rpx;
			margin-left: 30rpx;
			text-align: center;
		}
	}

	.list {
		display: flex;
		flex-direction: column;
		width: 690rpx;
		margin: 0 auto;
		background-color: #fff;
		border-radius: 12rpx;

		.item {
			display: flex;
			flex-direction: column;
			padding: 20rpx;
			border-bottom: 1px solid #ebebeb;

			.tit {
				font-size: 32rpx;
			}

			.address {
				font-size: 26rpx;
				color: #999;
			}
		}
	}

	.choosed_address-wrap {
		display: flex;
		align-items: center;
		justify-content: space-between;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding: 30rpx;
		// height: 98rpx;
		background-color: #fff;

		.choosed_address {
			font-size: 28rpx;
			flex: 1;
			padding-right: 20rpx;

			.tip {
				color: $yellow;
			}
		}

		.btn {
			font-size: 32rpx;
			color: #fff;
			width: 100rpx;
			text-align: center;
			height: 72rpx;
			line-height: 72rpx;
			background: $yellow;
			border-radius: 12rpx;
		}
	}
	.hint-wrap{
		width: 606rpx;
		height: 390rpx;
		.hint-content{
			height: calc(100% - 98rpx - 64rpx - 60rpx);
		}
	}
</style>
